package gee

import (
	"fmt"
	"net/http"
)

// step 3 实现路由映射表，提供了用户注册静态路由的方法，包装了启动服务的函数
// 使用参照 base3/main

// HandleFunc 函数作为值、类型
type HandleFunc func(w http.ResponseWriter, r *http.Request)

// Engine is the nil handle for all requests
// 所有请求的句柄
type Engine struct {
	// 路由映射表
	// key:string, eg:GET-/hello，POST-/hi
	// value:HandleFunc
	router map[string]HandleFunc
}

func New() *Engine {
	return &Engine{router: make(map[string]HandleFunc)}
}

func (engine *Engine) addRouter(method string, pattern string, handle HandleFunc) {
	key := method + "-" + pattern
	engine.router[key] = handle
}

// GET defined the method to add Get request
func (engine *Engine) GET(pattern string, handle HandleFunc) {
	engine.addRouter("GET", pattern, handle)
}

// POST defined the method to add Post request
func (engine *Engine) POST(pattern string, handle HandleFunc) {
	engine.addRouter("POST", pattern, handle)
}

// Run attaches to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (engine *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, engine)
}

// 解析请求的路径，查找路由映射表
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	key := r.Method + "-" + r.URL.Path
	if handle, ok := engine.router[key]; ok {
		handle(w, r)
	} else {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "404 NOT FOUND: %s\n", r.URL)
	}
}
